package com.bobamrz.frontend;

import java.util.Map;
import java.util.TreeMap;

import com.bobamrz.dao.DocTypeDAO;
import com.bobamrz.dao.IDocTypeDAO;

public class DocumentValidator {
	Map<String, Object> resultMap = new TreeMap<String, Object>();
	private IDocTypeDAO docTypeDAO;
	boolean isValid;
	
	public static String msg;
	public static String msgEmptyField = "empty field";
	public static String msgTooLong = "max 60 characters please";
	
	public DocumentValidator(){
		docTypeDAO = new DocTypeDAO();
	}
	
	public DocumentValidator(IDocTypeDAO docTypeDAO){
		this.docTypeDAO = docTypeDAO;
	}
	
	public Map<String, Object> execute(Map<String, String> parameters) {
		Map<String, String> errors = new TreeMap<String, String>();
		isValid = true;
		String id = parameters.get("id");
		String docType;
		if("new".equals(id)) {
			docType = parameters.get("docType");
		} else {
			docType = docTypeDAO.getDocTypeByDocumentId(Long.parseLong(id)).getTypeName();
		}
			
		for (Map.Entry<String, String> entry : parameters.entrySet()) {
			String paramName = entry.getKey();
			if("id".equals(paramName) || "docType".equals(paramName)) continue;
			String paramValue = entry.getValue();
			String errorMessage = "";
			errorMessage = validateParameter(docType, paramName, paramValue);

			if(!("".equals(errorMessage))) {
				isValid = false;
				errors.put(paramName, errorMessage);
			}
		}
		
		if(isValid) {
			resultMap.put("status", "success");
		} else {
			resultMap.put("status", "invalid");
			resultMap.put("errors", errors);
		}
		return resultMap;
	}
	
	private String validateParameter(String typeName, String param, String paramValue) {
		msg = "";
		if(param.equals("name") || param.equals("description")) {
			if("".equals(paramValue.trim())) {
				msg = msgEmptyField;
			}
		}
		boolean required = docTypeDAO.isAttributeRequired(typeName, param);
		if(required && paramValue.trim().length() < 1) {
			msg = msgEmptyField;
		}
		if(paramValue.length() > 60) {
			msg = msgTooLong;
		}
		return msg;
	}

	public IDocTypeDAO getDocTypeDAO() {
		return docTypeDAO;
	}

	public void setDocTypeDAO(IDocTypeDAO docTypeDAO) {
		this.docTypeDAO = docTypeDAO;
	}
	
	
}
